import React, { Component } from "react";
import {
  View,
  Text,
  StyleSheet,
  SafeAreaView,
  AsyncStorage,
  StatusBar,
  Alert
} from "react-native";
import { colors } from "../Style/Colors";
import Icon from "react-native-vector-icons/MaterialCommunityIcons";
import { withNavigation } from "react-navigation";
import Toast from "react-native-simple-toast";
import OfflineNotice from "./OfflineNotice";

export class Header extends Component {
  state = {
    isSearchActive: false
  };

  onLogout = () => {
    Alert.alert(
      "",
      "Are you sure you want log out?",
      [
        {
          text: "CANCEL",
          onPress: () => console.log("Cancels the log out"),
          style: "cancel"
        },
        {
          text: "LOG OUT",
          onPress: () => {
            AsyncStorage.removeItem("user-data")
              .then(() => {
                AsyncStorage.removeItem("loggedin-user")
                  .then(() => {
                    this.props.navigation.navigate("Login");
                  })
                  .catch(e => Toast.show(e.message));
              })
              .catch(e => Toast.show(e.message));
          }
        }
      ],
      { cancelable: false }
    );
  };

  onBack = () => {
    this.props.navigation.pop(1);
  };

  render() {
    const { isBack, text, isLogoutIcon, searchBar } = this.props;
    return (
      <SafeAreaView style={{ backgroundColor: colors.primaryColor }}>
        <View style={styles.container}>
          <StatusBar
            barStyle="light-content"
            hidden={false}
            backgroundColor={colors.primaryDarkColor}
          />
          {isBack && (
            <Icon
              onPress={this.onBack}
              name="arrow-left"
              size={24}
              color={colors.whiteColor}
            />
          )}
          <Text style={[styles.text, isBack && { marginLeft: 12 }]}>
            {text}
          </Text>
          {searchBar && (
            <Icon
              style={{ marginRight: 10 }}
              onPress={this.props.onSearchPress}
              name="magnify"
              size={24}
              color={colors.whiteColor}
            />
          )}

          {isLogoutIcon && (
            <Icon
              onPress={this.onLogout}
              name="logout"
              size={24}
              color={colors.whiteColor}
            />
          )}
        </View>
        <OfflineNotice />
      </SafeAreaView>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    padding: 14,
    backgroundColor: colors.primaryColor,
    flexDirection: "row"
  },
  text: {
    fontSize: 18,
    color: colors.whiteColor,
    fontWeight: "bold",
    flex: 1
  },
  textInput: {
    padding: 0,
    marginHorizontal: 10,
    fontSize: 16,
    flex: 1
  }
});

export default withNavigation(Header);
